package com.aoip.telemetry.telemetry.configureui.business.commonconfig.mergerule.service.impl;

import com.aoip.telemetry.telemetry.configureui.business.commonconfig.mergerule.mapper.MergeRuleGroupMapper;
import com.aoip.telemetry.telemetry.configureui.business.commonconfig.mergerule.service.MergeRuleGroupService;
import com.aoip.telemetry.telemetry.core.redis.RedisCache;
import com.aoip.telemetry.telemetry.entity.enums.CacheKeyEnum;
import com.aoip.telemetry.telemetry.entity.merge.DataMergeRuleGroupEntity;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;

/**
 * @author chenbai
 * @version 1.0
 * @date 2022/10/17 22:30
 */
@Service
@DS("telemetry")
public class MergeRuleGroupServiceImpl implements MergeRuleGroupService {
    @Resource
    private MergeRuleGroupMapper mapper;
    @Resource
    private RedisCache redisCache;

    @Override
    public List<DataMergeRuleGroupEntity> list(DataMergeRuleGroupEntity entity) {
        QueryWrapper<DataMergeRuleGroupEntity> queryWrapper = new QueryWrapper<>();
        String ruleGroupName = entity.getRuleGroupName();
        if (StringUtils.hasText(ruleGroupName)) {
            queryWrapper.like(true, "rule_group_name", ruleGroupName);
        }
        String ruleGroupTargetTable = entity.getRuleGroupTargetTable();
        if (StringUtils.hasText(ruleGroupTargetTable)) {
            queryWrapper.eq(true, "rule_group_target_table", ruleGroupTargetTable);
        }
        return mapper.selectList(queryWrapper);
    }

    @Override
    public DataMergeRuleGroupEntity detail(String id) {
        return mapper.selectById(id);
    }

    @Override
    public int insert(DataMergeRuleGroupEntity entity) {
        return mapper.insert(entity);
    }

    @Override
    public int update(DataMergeRuleGroupEntity entity) {
        return mapper.updateById(entity);
    }

    @Override
    public int initCache() {
        List<DataMergeRuleGroupEntity> list = list(new DataMergeRuleGroupEntity());
        Collection<String> keys = redisCache.keys(CacheKeyEnum.DATA_MERGE_RULE_GROUP + ":*");
        redisCache.deleteObject(keys);
        list.forEach(item -> redisCache.setCacheObject(CacheKeyEnum.DATA_MERGE_RULE_GROUP + ":" + item.getId(), item));
        return list.size();
    }

    @Override
    public void delete(Long[] ids) {
        mapper.deleteBatchIds(Arrays.asList(ids));
    }
}
